//
//  WJH_Tools.swift
//  EVOP
//
//  Created by LC_WJH on 2017/9/6.
//  Copyright © 2017年 gmc. All rights reserved.
//


//一些通用辅助函数写在这里

import Foundation

public class WJH_Tools {
    
    /*
        生成线路从首->到尾的属性字符
     */
    public static func genFromToArrowAttrText(from:String?,to:String?)->NSMutableAttributedString{
        
        let startStop:String = from ?? "";
        let endStop:String = to ?? "";
        
        let showText = String.init(format:"%@➞%@",startStop,endStop);
        
        //➞
        let AttrText = NSMutableAttributedString.init(string: showText);
        //默认blue
        AttrText.addAttributes(
            [NSAttributedString.Key.foregroundColor : UIColor.blue],
            range: NSRange.init(location: 0, length: showText.utf8.count));
        
        //箭头属性
        AttrText.addAttributes(
            [NSAttributedString.Key.font : "Zapf Dingbats 17.0"],
            range: NSRange.init(location: startStop.utf8.count, length: 1));
        AttrText.addAttributes(
            [NSAttributedString.Key.foregroundColor : UIColor.green],
            range: NSRange.init(location: startStop.utf8.count, length: 1));
        
        return AttrText;
    }
    
    
    
    //获取当前屏幕显示的最顶层的 viewcontroller
    public static func getTopestVC()->UIViewController?
    {
        WJH_Tools.searchNavicontrollerInChileVCDepth = 1;
        var result:UIViewController?;
        //UIresponse
        if result == nil {
            result = UIApplication.shared.keyWindow?.rootViewController;
            result = __getCurrentVC(result);
            if result != nil {
                print("Pop At target : \(result!.debugDescription)");
            }
        }
        
        return result;
    }
    
    /// 在获取当前topVC的过程中,搜索topVC的childviewcontroller中是否含有navigationcontroller,如果有,则继续搜寻navigationcontroller的topview
    ///这种逻辑使PopAlert即时在被嵌入的viewcontainer中也可以工作
    public static var searchNavicontrollerInChileVC = true;
    public static var searchNavicontrollerInChileVCDepth:Int = 1;
    
    //递归搜索顶层view
    fileprivate static func __getCurrentVC(_ tvc:UIViewController?)->UIViewController? {
        if let vcp = tvc?.presentedViewController{
            return __getCurrentVC(vcp);
        }
        if let nav = tvc as? UINavigationController {
            return  __getCurrentVC(nav.children.last);
        }
        if WJH_Tools.searchNavicontrollerInChileVC && WJH_Tools.searchNavicontrollerInChileVCDepth > 0 {
            if let child = tvc?.children {
                for c in child{
                    if let c_nav = c as? UINavigationController {
                        WJH_Tools.searchNavicontrollerInChileVCDepth -= 1;
                        return  __getCurrentVC(c_nav.children.last);
                    }
                }
            }
        }
        return tvc;
    }
    
    
    
    
    
    
    
    
    
}
